package com.meishij.fragment.finddetail;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.meishij.R;
import com.meishij.adapter.FindWenZhangRecyclerAdapter;
import com.meishij.adapter.ViewPagerAdapter;
import com.meishij.entry.FindWenZhangEntry;
import com.meishij.server.FindServer;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 阿飞 on 2016/10/14.
 */

public class FindWenZhangItemFragment extends Fragment {

    private String cid;
    private int page = 1;

    private static final String TAG = FindWenZhangItemFragment.class.getSimpleName();
    private ViewPager vpWenzhang;
    private RecyclerView recyclerViewWenzhang;
    private ViewPagerAdapter viewPagerAdapter;
    private FindWenZhangRecyclerAdapter recyclerAdapter;
    private Retrofit retrofit;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find_detail_wenzhang, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initArgument();
        initRetrofit();
        initView(view);
        requestNetData(cid, 1);
    }

    private void initArgument() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            cid = (String) arguments.get("cid");
        }
    }

    private void initView(View rootView) {
        vpWenzhang = (ViewPager) rootView.findViewById(R.id.vp_fragment_find_detail_wenzhang);
        viewPagerAdapter = new ViewPagerAdapter(getContext(), null);
        vpWenzhang.setAdapter(viewPagerAdapter);
        vpWenzhang.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int count = vpWenzhang.getAdapter().getCount();
                // 滑倒了最后一个
                if (position == count - 1) {
                    vpWenzhang.setCurrentItem(1, false);
                }
                // 滑倒了第一个
                if (position == 0) {
                    vpWenzhang.setCurrentItem(count - 1, false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        recyclerViewWenzhang = (RecyclerView) rootView.findViewById(R.id.recycler_fragment_find_detail_wenzhang);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerViewWenzhang.setLayoutManager(layoutManager);
        recyclerAdapter = new FindWenZhangRecyclerAdapter(getContext(), null);
        recyclerViewWenzhang.setAdapter(recyclerAdapter);
    }

    private void initRetrofit() {
        retrofit = new Retrofit.Builder()
                .baseUrl(FindServer.BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private void requestNetData(String cid, int page) {
        if (TextUtils.isEmpty(cid)) {
            Toast.makeText(getContext(), "找不到请求ID", Toast.LENGTH_SHORT).show();
            return;
        }
        FindServer findServer = retrofit.create(FindServer.class);

        Call<FindWenZhangEntry> call = findServer.getWenZhangResult(cid, String.valueOf(page), "android", "json");
        call.enqueue(new Callback<FindWenZhangEntry>() {
            @Override
            public void onResponse(Call<FindWenZhangEntry> call, Response<FindWenZhangEntry> response) {
                FindWenZhangEntry wenZhangEntry = response.body();

                // 先去除掉旧的数据
                viewPagerAdapter.clear();
                LayoutInflater inflater = LayoutInflater.from(getContext());
                List<FindWenZhangEntry.TopImgsBean> top_imgs = wenZhangEntry.getTop_imgs();
                // 添加最后一张图到最前
                FindWenZhangEntry.TopImgsBean firstImg = top_imgs.get(top_imgs.size() - 1);
                addImageToViewPager(firstImg.getPhoto(), inflater);
                // 按照顺序添加图
                for (FindWenZhangEntry.TopImgsBean top_img : top_imgs) {
                    String photo = top_img.getPhoto();
                    addImageToViewPager(photo, inflater);
                }
                // 添加第一张到最后
                FindWenZhangEntry.TopImgsBean endImg = top_imgs.get(0);
                addImageToViewPager(endImg.getPhoto(), inflater);
                // 设置第一次显示的图
                vpWenzhang.setCurrentItem(1);

                recyclerAdapter.addAll(wenZhangEntry.getList());
            }

            @Override
            public void onFailure(Call<FindWenZhangEntry> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void addImageToViewPager(String imageUrl, LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_find_detail_wenzhang_vp_item, null);
        SimpleDraweeView imageView = (SimpleDraweeView) view.findViewById(R.id.iv_fragment_find_detail_wenzhang_vp_item);
        if (!TextUtils.isEmpty(imageUrl)) {
            Uri photoUri = Uri.parse(imageUrl);
            imageView.setImageURI(photoUri);
        }
        viewPagerAdapter.add(view);
    }

}
